<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :labelCol="{ style: 'width:80px' }">
       <!-- 最小/最大/刻度 {{yAxisMin}}/ {{yAxisMax}}/ {{yAxisInterval}} -->
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="采样属性">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.property"
                dictCode="data_property where status = 1 and prop_type = '实时',prop_name,prop_no"
                placeholder="请选择属性名称"
                @change="peopertyChanage"
                ref="sltPeoperty"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="11" :md="12" :sm="24">
            <a-form-item label="采样范围">
              <a-range-picker v-model="queryParam.startEndDate" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="采样间隔">
              <a-input v-model="queryParam.distanceValue">
                <template #addonAfter>
                  <a-select v-model="queryParam.distanceUnit" style="width: 60px">
                    <a-select-option value="天">天</a-select-option>
                    <a-select-option value="时">时</a-select-option>
                    <a-select-option value="分">分</a-select-option>
                  </a-select>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="聚合方式">
              <a-select placeholder="请选择" default-value="平均值" v-model="queryParam.aggregation">
                <a-select-option value="平均值">平均值</a-select-option>
                <a-select-option value="方差">方差</a-select-option>
                <a-select-option value="均方根">均方根</a-select-option>
                <a-select-option value="偏度">偏度</a-select-option>
                <a-select-option value="峭度">峭度</a-select-option>
                <a-select-option value="波形因子">波形因子</a-select-option>
                <a-select-option value="峰值因子">峰值因子</a-select-option>
                <a-select-option value="脉冲因子">脉冲因子</a-select-option>
                <a-select-option value="裕度因子">裕度因子</a-select-option> 
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="槽号">
              <a-select show-search placeholder="请选择槽号" v-model="queryParam.dataSoltIds">
                <a-select-option v-for="item in slotIdList" :key="item" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="滚动">
              <a-input v-model="queryParam.scrollValue">
                <a-select slot="addonBefore" default-value="向前" v-model="queryParam.scroll">
                  <a-select-option value="向前">向前</a-select-option>
                  <a-select-option value="向后">向后</a-select-option>
                </a-select>
                <a-select slot="addonAfter" defaultValue="天" v-model="queryParam.scrollUnit" style="width: 60px">
                  <a-select-option value="天">天</a-select-option>
                  <a-select-option value="时">时</a-select-option>
                  <a-select-option value="分">分</a-select-option>
                </a-select>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24"> 
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-spin :spinning="loading">
      <a-tabs defaultActiveKey="1">
        <!-- 柱状图 -->
        <a-tab-pane tab="图表" key="1">
          <!-- <bar title=""  :key="new Date().getTime()" :dataSource="barData" :height="height" />  -->
          <!-- <transfer-bar title="年度消耗流量一览表" :data="barData" x="日期" y="电压(V)" :height="height"/> -->
          <div id="main" :style="{ width: '100%', height: height + 'px' }"></div>
        </a-tab-pane>
        <!-- 多列柱状图 -->
        <a-tab-pane tab="数据" key="2">
          <a-table ref="table" size="default" :columns="columns" :data-source="barData2" />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </a-card>
</template>

<script>
import * as echarts from 'echarts'
import Bar from '@/components/chart/Bar'
import LineChartMultid from '@/components/chart/LineChartMultid'
import TransferBar from '@/components/chart/TransferBar'
import STable from '@/components/table/'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import AInput from 'ant-design-vue/es/input/Input'
import moment from 'moment'
import axios from 'axios'
import { httpAction, getAction } from '@/api/manage'

export default {
  name: 'TableList',
  components: {
    Bar,
    LineChartMultid,
    TransferBar,
    AInput,
    ATextarea,
    STable,
  },
  data() {
    return {
      height: document.body.clientHeight - 357,
      slotIdList: [],
      barData: [],
      barData2: [],
      fields: ['电压'], 
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      }, 
      // 查询参数
      queryParam: {
        distanceValue: '1', //采样间隔
        distanceUnit: '时',
        scroll: '向前',
        scrollValue: '1',
        scrollUnit: '天',
        property: 'electric', //采样属性
        startDate: '', //
        endDate: '', //
        startEndDate: [], //
        aggregation: '平均值', //聚合方式
        dataSoltIds: '',
      },
      // 表头
      columns: [
        {
          title: '时间',
          dataIndex: 'date',
          width: '200px',
        },
        {
          title: '槽号',
          dataIndex: 'soltId',
          needTotal: true,
          customRender: (text) => text,
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {},

      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      propertyName: '', //
      yAxisInterval: 0.2, //0.2
      yAxisMin: 4, //最小刻度
      yAxisMax: 4.2, //最大刻度
    }
  },
  created() {
    this.loadDataSlot()
    this.resetSearchForm()
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        that.height = document.body.clientHeight - 357
      })()
    }
  },
  methods: {
    sortBykey(ary, key) {
      return ary.sort(function (a, b) {
        let x = a[key]
        let y = b[key]
        return x < y ? -1 : x > y ? 1 : 0
      })
    },
    loadDataSlot() {
      getAction('/dataSlot/dataSlot/list', { pageSize: 9999 })
        .then((res) => {
          if (res.success) {
            var dataSource = res.result.records
            for (let i = 0; i < dataSource.length; i++) {
              this.slotIdList.push(dataSource[i].slotId)
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.loadBarData()
    },
    loadData2(x, y, max, min, before = '', after = '') {
      let data = []
      for (let i = 0; i < 12; i += 1) {
        data.push({
          [x]: `${before}${i + 1}${after}`,
          [y]: Math.floor(Math.random() * max) + min,
        })
      }
      return data
    },
    // 加载柱状图数据
    loadBarData() {
      var that = this
      if(!that.queryParam.property){
        this.$message.warning('请选择采样属性')
        return
      } 
      if (that.queryParam.dataSoltIds.length == 0) {
        this.$message.warning('请选择槽号')
        return
      }
      if (that.queryParam.startEndDate) {
        that.queryParam.startDate = moment(that.queryParam.startEndDate[0]).format('YYYY-MM-DD')
        that.queryParam.endDate = moment(that.queryParam.startEndDate[1]).format('YYYY-MM-DD')
      }

      that.fields = [that.queryParam.dataSoltIds]
      that.columns = [
        {
          title: '时间',
          dataIndex: 'date',
          width: '200px',
        },
        {
          title: '值',
          dataIndex: that.queryParam.property,
          needTotal: true,
          customRender: (text) => text,
        },
      ]
      var param = Object.assign({}, that.queryParam)
      param.dataSoltIds = [param.dataSoltIds]
      param.isOnlyOne = true //单槽
      that.loading = true
      httpAction('/external/hadoop/roll/slots', param, 'post')
        .then((res) => {
          if (res.success) {
            if(res.result&&res.result.length==0){
               this.$message.warning("没有找到符合条件的数据")
              return;
            }
            that.barData2 = []
            that.barData = []
            var data = res.result

            that.barData2 = that.sortBykey(Object.assign(that.barData2, data), 'date')

            data.forEach((e) => {
              that.barData.push({
                x: e.date,
                y: parseFloat(e[that.queryParam.property]),
              })
            })
            var bb = that.sortBykey(data, that.queryParam.property)
            that.yAxisMin = Math.floor(bb[0][that.queryParam.property] * 10) / 10 // Math.trunc(bb[0][that.queryParam.property]) //向下取整
            that.yAxisMax = parseFloat(parseFloat(that.upFixed(bb[bb.length - 1][that.queryParam.property], 2))+0.01).toFixed(2) //Math.ceil(bb[bb.length - 1][that.queryParam.property]) //向上取整
            that.yAxisInterval = parseFloat(((that.yAxisMax - that.yAxisMin) / 10).toFixed(1))
            if (that.yAxisInterval == 0) {
              that.yAxisInterval = 0.02
            }
            that.loadTb()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loading = false
        })

      // this.barData = this.loadData2('x', 'y', 1000, 200)
    },
    upFixed(num, fix) {//向上取整
      // num为原数字，fix是保留的小数位数
      let result = '0'
      if (Number(num) && fix > 0) {
        // 简单的做个判断
        fix = +fix || 2
        num = num + ''
        if (/e/.test(num)) {
          // 如果是包含e字符的数字直接返回
          result = num
        } else if (!/\./.test(num)) {
          // 如果没有小数点
          result = num + `.${Array(fix + 1).join('0')}`
        } else {
          // 如果有小数点
          num = num + `${Array(fix + 1).join('0')}`
          let reg = new RegExp(`-?\\d*\\.\\d{0,${fix}}`)
          let floorStr = reg.exec(num)[0]
          if (+floorStr >= +num) {
            result = floorStr
          } else {
            let floorNumber = +floorStr + +`0.${Array(fix).join('0')}1`
            let point = /\./.test(floorNumber + '') ? '' : '.'
            let floorStr2 = floorNumber + point + `${Array(fix + 1).join('0')}`
            result = reg.exec(floorStr2)[0]
          }
        }
      }
      return result
    }, 
    resetSearchForm() {
      var that = this;
      this.queryParam = {
        property: '', //采样属性
        startDate: moment(new Date()).format('YYYY-MM') + '-01', //
        endDate: moment(new Date()).format('YYYY-MM-DD'), //
        distanceValue: '1',
        distanceUnit: '时',
        scroll: '向前',
        scrollValue: '1',
        scrollUnit: '天',
        aggregation: '平均值',
        dataSoltIds: '',
      }
      this.$set(that.queryParam, "startEndDate", [that.queryParam.startDate, that.queryParam.endDate])  
    },
    loadTb() {
      var that = this
      var chartDom = document.getElementById('main')
      var myChart = echarts.init(chartDom)
      var option
      let date = []
      let data = []
      for (let i = 0; i < that.barData.length; i++) {
        date.push(that.barData[i]['x'])
        data.push(that.barData[i]['y'])
      }
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          position: function (pt) {
            return [pt[0], '10%']
          },
        },
        title: {
          left: 'center',
          text: '[ ' + that.propertyName + ' ] 滚动分析',
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: date,
          // axisLabel: {
          //     interval: 30, // 显示所有刻度
          //     rotate: 30 // 将刻度旋转30度
          // }
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          interval: that.yAxisInterval, //分割刻度
          min: that.yAxisMin,
          max: that.yAxisMax,
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
          },
        ],
        series: [
          {
            name: that.propertyName,
            type: 'line',
            smooth: true,
            // symbol: 'none',
            // sampling: 'lttb',
            itemStyle: {
              color: 'rgb(255, 70, 131)',
            },
            // areaStyle: {
            //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            //     {
            //       offset: 0,
            //       color: 'rgb(255, 158, 68)',
            //     },
            //     {
            //       offset: 1,
            //       color: 'rgb(255, 70, 131)',
            //     },
            //   ]),
            // },
            data: data,
          },
        ],
      }

      option && myChart.setOption(option)
      window.onresize = function () {
        setTimeout(function () {
          myChart.resize()
        }, 10)
      }
    },
    peopertyChanage(v) {
      var that = this
      var obj = this.$refs.sltPeoperty.dictOptions.find((o) => o.value == v)
      if (obj) {
        that.propertyName = obj.text
      }
    },
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  },
}
</script>